from django.db.models import Q
from django.utils import timezone
from rest_framework import status, mixins
from rest_framework.decorators import action
from rest_framework.generics import ListAPIView,UpdateAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.viewsets import ViewSet, GenericViewSet
from recruits.models import City, Recruit, Enterprise
from recruits.serializers.city import CityHotlistSerializers, SearchRecommandSerializers, \
    SearchHotlistEnterpriseSerializers, EnterpriseCollectSerializers
from recruits.serializers.enterprises import EnterpriseViewSerializers, AddEnterpriseVisitViewSerializers
from recruits.serializers.jobs import RecruitsViewSerializers, AddRecruitsVisitViewSerializers, \
    RecruitCollectSerializers,SearchJobViewSerializer
from users.models import User


class CityHotlistView(ListAPIView):
    '''热门城市类视图'''
    serializer_class = CityHotlistSerializers

    queryset = City.objects.filter(ishot=1)

    pagination_class = None


class AddEnterpriseVisitView(UpdateAPIView):
    '''增加企业访问次数'''
    serializer_class = AddEnterpriseVisitViewSerializers

    queryset = Enterprise.objects.filter()

    def update(self, request, *args, **kwargs):

        id = kwargs.get('pk')

        try:

            visits = self.get_object().visits

            self.get_queryset().update(visits=visits+1)

            data = {"id": id, "success": True, "message": "ok"}

        except Exception:

            data = {"id": id, "success": False, "message": "fail"}

        return Response(data,status=status.HTTP_200_OK)


class SearchRecommendView(ListAPIView):
    '''推荐职位视图'''
    serializer_class = SearchRecommandSerializers

    queryset = Recruit.objects.filter(state=1)

    pagination_class = None


class SearchLatestView(ListAPIView):
    '''最新职位类视图'''
    serializer_class = SearchRecommandSerializers

    now_date = timezone.now().replace(hour=0, minute=0, second=0, microsecond=0)

    queryset = Recruit.objects.filter(createtime__gte=now_date-timezone.timedelta(days=30))

    pagination_class = None


class SearchHotlistEnterpriseView(ListAPIView):
    '''热门企业类视图'''
    serializer_class = SearchHotlistEnterpriseSerializers

    queryset = Enterprise.objects.filter(visits__gte=10)

    pagination_class = None


class RecruitsView(mixins.RetrieveModelMixin,GenericViewSet):
    '''职位详情类视图'''

    serializer_class = RecruitsViewSerializers

    queryset = Recruit.objects.all()

    lookup_value_regex = '\d+'


class AddRecruitsVisitView(UpdateAPIView):
    '''增加职位访问次数'''

    serializer_class = AddRecruitsVisitViewSerializers

    queryset = Recruit.objects.filter()

    def update(self, request, *args, **kwargs):

        id = kwargs.get('pk')

        try:

            visits = self.get_object().visits

            self.get_queryset().update(visits=visits+1)

            data = {"id": id, "success": True, "message": "ok"}

        except Exception:

            data = {"id": id, "success": False, "message": "fail"}

        return Response(data,status=status.HTTP_200_OK)



class RecruitCollectView(mixins.UpdateModelMixin,GenericViewSet):
    '''收藏职位视图'''
    permission_classes = [IsAuthenticated]
    serializer_class = RecruitCollectSerializers

    @action(methods=['post'],detail=True)
    def collect(self,request,pk):

        try:
            instances = Recruit.objects.get(id=pk)
            user = User.objects.get(username=request.user.username)
            instances.users.add(user.id)

        except Exception:

            data = {"id": pk, "message": "收藏失败", "success": False}

        else:

            data = {"id": pk, "message": "ok", "success": True}

        return Response(data,status=status.HTTP_201_CREATED)

    lookup_value_regex = '\d+'


class EnterpriseView(mixins.RetrieveModelMixin,GenericViewSet):
    '''企业详情类视图'''

    serializer_class = EnterpriseViewSerializers
    queryset = Enterprise.objects.all()

    lookup_value_regex = '\d+'


class EnterpriseCollectView(mixins.UpdateModelMixin,ViewSet):
    '''收藏公司视图'''
    permission_classes = [IsAuthenticated]

    serializer_class = EnterpriseCollectSerializers

    @action(methods=['post'], detail=True)
    def collect(self, request, pk):

        try:
            instances = Enterprise.objects.get(id=pk)
            user = User.objects.get(username=request.user.username)
            instances.users.add(user.id)

        except Exception:

            data = {"id": pk, "message": "收藏失败", "success": False}

        else:

            data = {"id": pk, "message": "ok", "success": True}

        return Response(data, status=status.HTTP_201_CREATED)

    lookup_value_regex = '\d+'


class SearchJobView(GenericViewSet):
    '''搜索职位'''

    serializer_class = SearchJobViewSerializer

    def search(self,request):
        '''post请求'''
        city = request.data.get('cityname')

        jobname = request.data.get('keyword')

        queryset = Recruit.objects.filter(Q(jobname__contains=jobname)|Q(city=city))

        serializers = self.serializer_class(queryset,many=True)

        return Response(serializers.data,status=status.HTTP_200_OK)





